import {createStore, applyMiddleware, combineReducers} from 'redux'
import thunk  from 'redux-thunk'
import React, { Component } from 'react';
import { composeWithDevTools } from 'redux-devtools-extension'
import {reducers} from '@/store/reducers';
import { initData } from '@/utils/index';

let store
const __NEXT_REDUX_STORE = '__NEXT_REDUX_STORE';

// const getOrCreateStore = (initialState) => {
//     if (typeof window === 'undefined') {
//         return initStore(initialState);
//     }
//     // 客户端切换都会触发，保证客户端只有一个store，需要判断处理
//     if (!window[__NEXT_REDUX_STORE]) {
//         window[__NEXT_REDUX_STORE] = createStore(initialState);
//     }
//     return window[__NEXT_REDUX_STORE];
// };

function initStore(initialState) {
  return createStore(
    reducers,
    initialState,
    composeWithDevTools(applyMiddleware(thunk))
  )
}

const initializeStore = (preloadedState = initData) => {
  let _store = store ?? initStore(preloadedState)

  // After navigating to a page with an initial Redux state, merge that state
  // with the current state in the store, and create a new store
  if (preloadedState && store) {
    _store = initStore({
      ...store.getState(),
      ...preloadedState,
    })
    // Reset the current store
    store = undefined
  }

  // For SSG and SSR always create a new store
  if (typeof window === 'undefined') return _store
  // Create the store once in the client
  if (!store) store = _store

  return _store
}
export default initializeStore
